﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ls.Utils
{
    public static class SxHttpContext
    {
        public static IApplicationBuilder ServiceProvider;
        static SxHttpContext()
        { }

        /// <summary>
        /// 获取当前上下文
        /// </summary>
        public static HttpContext Current
        {
            get
            {
                object factory = ServiceProvider.ApplicationServices.GetService(typeof(IHttpContextAccessor));

                HttpContext context = ((HttpContextAccessor)factory).HttpContext;
                return context;
            }
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>() where T : class
        {
            if (ServiceProvider == null)
            {
                return default(T);
            }
            else
            {
                try
                {
                    return ServiceProvider.ApplicationServices.GetService(typeof(T)) as T;
                }
                catch (Exception ex)
                {

                    return null;
                }
             
            }
        }
        public static string GetUserIp()
        { 
            return Current.GetUserIp();
        }
        public static string GetUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }
    }
}
